package casa.depesos.app.com.dlg;

import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.core.text.HtmlCompat;

import com.common.base.utils.WeakHandler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import casa.depesos.app.com.databinding.RightDlgBinding;
import casa.depesos.app.com.http.ReqCallback;
import casa.depesos.app.com.http.bean.AgreeBean;
import casa.depesos.app.com.http.req.GetAgreeReq;
import casa.depesos.app.com.utils.Report;
import casa.depesos.app.com.utils.html.MyHtml;
import casa.depesos.app.com.utils.html.SpanTagHandler;
import casa.depesos.app.com.view.CustomScrollView;

public class RightDlg extends FullScreenDlg {

    RightDlgBinding binding;
    boolean sms = false;

    public RightDlg setSms() {
        sms = true;
        return this;
    }

    private CharSequence getDefault() {
        try {
            InputStream inputStream = getActivity().getAssets().open(sms ? "sms" : "right");
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
            String fileContent = stringBuilder.toString();
            // 关闭InputStream
            inputStream.close();
            // 将json字符串转换成List
            List<Pair<Integer, Integer>> list = new ArrayList<>();
            int i = fileContent.indexOf("https://");
            while (true) {
                if (i < 0) {
                    break;
                }
                int j = fileContent.indexOf(".net", i);
                if (j >= 0) {
                    list.add(new Pair(i, j + 4));
                    i = fileContent.indexOf("https://", j);
                } else {
                    break;
                }
            }

            String mail = "finabsacpe@gmail.com";
            i = fileContent.indexOf(mail);
            while (true) {
                if (i < 0) {
                    break;
                }
                int end = i + mail.length();
                list.add(new Pair<>(i, end));
                i = fileContent.indexOf(mail, end);
            }

            SpannableString msp = new SpannableString(fileContent);
            for (Pair<Integer, Integer> p : list) {
                msp.setSpan(new ForegroundColorSpan(0xff5B79FF), p.first, p.second, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            return msp;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private void get() {
        showLoading();
        new GetAgreeReq(sms ? "4" : "3").req(new ReqCallback<AgreeBean>() {
            @Override
            public void callback(boolean success, AgreeBean bean) {
                hideLoading();
                if (success && bean.isValid()) {
                    binding.tv.setText(HtmlCompat.fromHtml(bean.data.content, HtmlCompat.FROM_HTML_MODE_LEGACY));
//                    try {
//                        binding.tv.setText(MyHtml.fromHtml(bean.data.content, null, new SpanTagHandler()));
//                    } catch (Throwable e) {
//                        binding.tv.setText(HtmlCompat.fromHtml(bean.data.content, HtmlCompat.FROM_HTML_MODE_LEGACY));
//                    }
                } else {
                    CharSequence tmp = getDefault();
                    if (!TextUtils.isEmpty(tmp)) {
                        binding.tv.setText(tmp);
                    }
                }
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        setCancelable(false);
        binding = RightDlgBinding.inflate(inflater, container, false);
        binding.tv.setMovementMethod(LinkMovementMethod.getInstance());
        binding.ok.setOnClickListener(view -> dismiss(true, null));
//        if (sms) {
//            binding.title.setText("Instrucción de permisos de SMS");
//        }
        get();
        binding.scroll.setOnScrollChangeListener(new CustomScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollToStart() {

            }

            @Override
            public void onScrollToEnd() {
                enable();
            }
        });

        new WeakHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (binding.scroll.isScrolledToBottom()) {
                    enable();
                }
            }
        }, 500);

        return binding.getRoot();
    }

    boolean report = false;

    private void enable() {
        if (report) {
            return;
        }
        report = true;
        Report.show("ACTION_VV_004");
        binding.ok.setEnabled(true);
        binding.ok.setAlpha(1f);
    }
}
